package com.movieknight;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.github.savvasdalkitsis.jtmdb.Movie;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

// Movies Tab. Displays a list of current movies, and contains a menu

public class MoviesActivity extends Activity {
	private static final String LOG_TAG = TMDBMovieDownloader.class.getSimpleName();
	private List<Movie> displayMovies;
	private SQLMoviesDataSource datasource;
	List<SQLMovie> values = new ArrayList<SQLMovie>();
	
	// Return values.
    static final int PICK_MOVIE_REQUEST = 0;
    static final int DELETE_MOVIE_REQUEST = 1;
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        values = new ArrayList<SQLMovie>();
        displayMovies = new ArrayList<Movie>();
		datasource = new SQLMoviesDataSource(this);
		datasource.open();
		/*

        //Convert SQLMovies ints into TMDBMovies
        displayMovies = new ArrayList<Movie>();
        for(int i = 0; i < values.size(); i++) {
			try {
		        Movie temp = Movie.getInfo(values.get(i).getMovie());
				displayMovies.add(temp);
			} catch (IOException e) {
				Log.w(LOG_TAG, "IO Excpetion while fetching movie ID" + 27205, e);
			} catch (JSONException e) {
				Log.w(LOG_TAG, "JASONException while fetching movie ID" + 27205, e);
			}
        }*/
		
		String FILENAME = "username";
		String newUser = ((MovieKnightApp) this.getApplication()).getUsername();
		String oldUser = new String();;

		FileInputStream fis;
		try {
			fis = openFileInput(FILENAME);
			InputStreamReader in = new InputStreamReader(fis);
			BufferedReader br = new BufferedReader(in);
			oldUser = br.readLine();
		} catch (FileNotFoundException e2) {
			Log.v(LOG_TAG, "File Not Found");
		} catch (IOException e) {
			Log.v(LOG_TAG, "IOException");
		}
		
		Log.v(LOG_TAG, "oldUser: " + oldUser);
		
		FileOutputStream fos;
		try {
			fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
			fos.write(newUser.getBytes());
			fos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Log.v(LOG_TAG, "newUser: " + newUser);
		
		if(newUser.toLowerCase() != oldUser.toLowerCase()) {
			refreshMovies();
		}
        
		// Display list of movies.
		/*ListView listView = new ListView(getBaseContext());
		listView.setAdapter(new MovieAdapter(getBaseContext(), displayMovies, (MovieKnightApp) getApplication()));
		this.setContentView(listView);
        
		
		// setOnItemClickListener looks for items being clicked.
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(@SuppressWarnings("rawtypes") AdapterView parent, View v, int position, long id) {
				Intent intent = new Intent(getBaseContext(), MovieInfoPageActivity.class);
				intent.putExtra("movieID", (int) id);
				startActivityForResult(intent, 0);
			}
		});*/
    }

    // Creates menu when phone's hardware menu button is pressed.
    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.movies_menu, menu);
        return true;
    }
    
    // Switch statement when a menu option is selected.
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.addMovie:
                startActivityForResult(new Intent(MoviesActivity.this,AddMovieSearchBrowser.class), PICK_MOVIE_REQUEST);
                return true;
            case R.id.deleteMovie:
            	if(values.size() != 0) {
                    startActivityForResult(new Intent(MoviesActivity.this,MoviesDeleteActivity.class), DELETE_MOVIE_REQUEST);
                    return true;
            	}
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    // This function receives the result of the activities launched from the menu.
    // If statements determine which activity is returning the result.
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PICK_MOVIE_REQUEST) {
            if (resultCode == RESULT_OK) {
        		try {
        			// SERVER: Create movie with TMDB ID: data.getExtras().getInt("returnKey1")
        			Movie temp = Movie.getInfo(data.getExtras().getInt("returnKey1"));
        			String imdb = temp.getImdbID();
        			Socket server = ((MovieKnightApp) this.getApplication()).getServer();
        			String sessionID = ((MovieKnightApp) this.getApplication()).getSessionID();
        			int tempError = -1;
        			
        			PrintWriter out = null;
					out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(server.getOutputStream())), true);
					out.println("{\"module\": \"movies\", \"method\": \"add_movie\",\"session_id\": \"" + sessionID + "\", \"params\": {\"movie_id\": \"" + imdb + "\"}}");
					
					BufferedReader input;
					String st = null;
			        input = new BufferedReader(new InputStreamReader(server.getInputStream()));    
					st = input.readLine();//Get Response from Server		
					JSONObject jsonObject = null;	
					
					//Parse response
					jsonObject = new JSONObject(st);
				
					//Error Code
					tempError = Integer.parseInt(jsonObject.getString("error_code"));
					//END SERVER ------------------------------------------------------
					
					if(tempError==0){
						refreshMovies();
	        			/*datasource.createMovie(data.getExtras().getInt("returnKey1"));
	        	        Movie newMovie = Movie.getInfo(data.getExtras().getInt("returnKey1"));
	        			displayMovies.add(newMovie);
	        			ListView listView = new ListView(getBaseContext());
	        			listView.setAdapter(new MovieAdapter(getBaseContext(), displayMovies, (MovieKnightApp) getApplication()));
	        			this.setContentView(listView);
	        			listView.setOnItemClickListener(new OnItemClickListener() {
	        				public void onItemClick(@SuppressWarnings("rawtypes") AdapterView parent, View v, int position, long id) {
	        					Intent intent = new Intent(getBaseContext(), MovieInfoPageActivity.class);
	        					intent.putExtra("movieID", (int) id);
	        					startActivityForResult(intent, 0);
	        				}
	        			});*/
					}
        		} catch (IOException e) {
        			Log.w(LOG_TAG, "IO Excpetion while fetching movie ID" + data.getExtras().getInt("returnKey1"), e);
        		} catch (JSONException e) {
        			Log.w(LOG_TAG, "JASONException while fetching movie ID" + data.getExtras().getInt("returnKey1"), e);
        		}
            }
        }
        if(requestCode == DELETE_MOVIE_REQUEST) {
        	if(resultCode == RESULT_OK) {
        		refreshMovies();
        		/*//Convert SQLMovies ints into TMDBMovies
        		values = datasource.getAllMovies();
                displayMovies = new ArrayList<Movie>();
                for(int i = 0; i < values.size(); i++) {
        			try {
        		        Movie temp = Movie.getInfo(values.get(i).getMovie());
        				displayMovies.add(temp);
        			} catch (IOException e) {
        				Log.w(LOG_TAG, "IO Excpetion while fetching movie ID" + 27205, e);
        			} catch (JSONException e) {
        				Log.w(LOG_TAG, "JASONException while fetching movie ID" + 27205, e);
        			}
                }
        		// Display list of movies.
        		ListView listView = new ListView(getBaseContext());
        		listView.setAdapter(new MovieAdapter(getBaseContext(), displayMovies, (MovieKnightApp) getApplication()));
    			this.setContentView(listView);
    			listView.setOnItemClickListener(new OnItemClickListener() {
    				public void onItemClick(@SuppressWarnings("rawtypes") AdapterView parent, View v, int position, long id) {
    					Intent intent = new Intent(getBaseContext(), MovieInfoPageActivity.class);
    					intent.putExtra("movieID", (int) id);
    					startActivityForResult(intent, 0);
    				}
    			});*/
        	}
        }
    }
    
   public void refreshMovies(){
	// SERVER: Refresh Friends List
		if(values!=null)
			values.clear();
		Socket server = ((MovieKnightApp) this.getApplication()).getServer();
		String sessionID = ((MovieKnightApp) this.getApplication()).getSessionID();
		int tempError = -1;
				
		PrintWriter out = null;
		try {
			out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(server.getOutputStream())), true);	
			out.println("{\"module\": \"movies\", \"method\": \"get_movies\",\"session_id\": \"" + sessionID + "\"}");
					
			BufferedReader input = null;
			String st = null;
			input = new BufferedReader(new InputStreamReader(server.getInputStream()));    
			st = input.readLine();//Get Response from Server		
			JSONObject jsonObject = null;
			JSONArray jsonArray = null;
				
			//Parse response
			try {
				jsonObject = new JSONObject(st);
				jsonArray = jsonObject.getJSONArray("movies");
			
				//Error Code
				tempError = Integer.parseInt(jsonObject.getString("error_code"));
				
			//END SERVER ------------------------------------------------------
			
			if(tempError ==0)
			{
				
				for(int i = 0; i < jsonArray.length(); i++){
					List<Movie> tempList = Movie.imdbLookup(jsonArray.getString(i));
					if(tempList.size()>0)
					{
						Movie temp = tempList.get(0);
						SQLMovie tempSQLMovie = new SQLMovie((long)i, temp.getID());
						
						values.add(tempSQLMovie);
						Log.v("movie", jsonArray.getString(i));
					}
				}
				
				//Convert SQLMovies ints into TMDBMovies
        		//values = datasource.getAllMovies();
                displayMovies = new ArrayList<Movie>();
                for(int i = 0; i < values.size(); i++) {
        			try {
        		        Movie temp = Movie.getInfo(values.get(i).getMovie());
        				displayMovies.add(temp);
        			} catch (IOException e) {
        				Log.w(LOG_TAG, "IO Excpetion while fetching movie ID" + 27205, e);
        			} catch (JSONException e) {
        				Log.w(LOG_TAG, "JASONException while fetching movie ID" + 27205, e);
        			}
                }
        		// Display list of movies.
        		ListView listView = new ListView(getBaseContext());
        		listView.setAdapter(new MovieAdapter(getBaseContext(), displayMovies, (MovieKnightApp) getApplication()));
    			this.setContentView(listView);
    			listView.setOnItemClickListener(new OnItemClickListener() {
    				public void onItemClick(@SuppressWarnings("rawtypes") AdapterView parent, View v, int position, long id) {
    					Intent intent = new Intent(getBaseContext(), MovieInfoPageActivity.class);
    					intent.putExtra("movieID", (int) id);
    					startActivityForResult(intent, 0);
    				}
    			});
   			
			}
			
			} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
   }
}